#import "Controller.h"
#import "MyView.h"

// http://www.codeproject.com/cs/media/IdealTextColor.asp?forumid=363054&exp=0&df=100&select=1780021#xx1780021xx

@implementation Controller

-(void) awakeFromNib
{
// This isn't working?  Not sure why...
//	[[NSColorPanel sharedColorPanel] setDelegate:self];

// This, on the other hand, does... changeColor: is the delegate method, so 
// it's kinda 6-of-one, half-dozen of another.
	[[NSColorPanel sharedColorPanel] setTarget:self];
	[[NSColorPanel sharedColorPanel] setAction:@selector(changeColor:)];

	[[NSColorPanel sharedColorPanel] setContinuous:YES];
	[[NSColorPanel sharedColorPanel] setColor:[NSColor whiteColor]];
	[[NSColorPanel sharedColorPanel] orderFront:nil];
}


-(void) changeColor:(id)colorPanel
{
	[myText setTextColor:[self idealTextColor:[colorPanel color]]];

	[myHexValue setStringValue:[self hexValueOfColor:[colorPanel color]]];

	[myView setBGColor:[colorPanel color]];
}

// http://paste.lisp.org/display/40952
-(NSColor *) idealTextColor:(NSColor *) bkgrdColor
{
	float threshold = 0.411765;
	float red, green, blue, alpha;

    [bkgrdColor getRed:&red green:&green blue:&blue alpha:&alpha];
    float bgDelta = (red * 0.299 + green * 0.587 + blue * 0.114);

    return 1.0 - bgDelta < threshold ? [[NSColor blackColor] autorelease] : [[NSColor whiteColor] autorelease];
}

-(NSString *) hexValueOfColor:(NSColor *)color
{
	float red, green, blue;

	[color getRed:&red green:&green blue:&blue alpha:NULL];
	return( [NSString stringWithFormat:@"#%02X%02X%02X", (int)(red * 255), (int)(green * 255), (int)(blue * 255)] );
}

@end
